package com.wx.house.terminal.api.wxpay.controller;

import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.exception.UserException;
import com.wx.house.core.mapper.order.TOrderMapper;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.po.TOrder;
import com.wx.house.terminal.api.wxpay.conf.WXConfigUtil;
import com.wx.house.terminal.api.wxpay.sdk.WXPayConstants;
import com.wx.house.terminal.api.wxpay.sdk.WXPayUtil;
import com.wx.house.terminal.api.wxpay.service.impl.WxServiceImpl;
import com.wx.house.terminal.api.wxpay.vo.PayResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay/weixin")
@Api(tags = "微信支付")
    public class WXController extends BaseController{

    @Autowired
    private WxServiceImpl wxPayService;
    @Autowired
    private TOrderMapper tOrderMapper;
    /**
     * 统一下单
     * 官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapte9_1r=
     *
     * @param outTradeNo
     * @param totalFee
     * @return
     * @throws Exception
     */
    @ApiOperation("统一下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "totalFee", value = "订单金额",required = true),
            @ApiImplicitParam(name = "outTradeNo", value = "系统订单号",required = true)
    })

    @PostMapping("/apppay.json")
    public Result wxPay(@RequestParam(value = "totalFee") String totalFee, @RequestParam(value = "outTradeNo") String outTradeNo) throws Exception {
        WXConfigUtil config = new WXConfigUtil();
        String user_id=this.getUserId();//this.getUserId();
        String attach = "{\"user_id\":\"" + user_id + "\"}";
        //请求预支付订单
        totalFee=String.valueOf(new DecimalFormat("0").format(new BigDecimal(totalFee).multiply(new BigDecimal(100))));
        //查询订单编号查看订单编号是否已经支付,如果未支付查询预付订单id是否生产大于两小时,如果大于了两小时则重新调用微信预付订单接口
        TOrder tOrder=tOrderMapper.selectTorder(outTradeNo);
        
        TOrder selectTorId = tOrderMapper.selectTorId(outTradeNo);
        if(selectTorId.getActualPrice().multiply(new BigDecimal(100)).compareTo(new BigDecimal(totalFee))!=0) {
        	 throw new BusinessException("付款金额与订单金额不匹配");
        }
        
        Calendar calendar = Calendar.getInstance();
        if(ObjectUtils.isEmpty(tOrder)) {
        	throw new UserException("订单信息错误",201);
        }else {
        	if(ObjectUtils.isEmpty(tOrder.getLatestTime())) {
        		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        		calendar.setTime(sdf.parse("2000-01-01"));
        	}else {
        		calendar.setTime(tOrder.getLatestTime());
        	}
             //最近一次发起支付时间加二小时
             calendar.add(Calendar.HOUR_OF_DAY, 2);
        }
        Map<String, String> map = new HashMap<>();
        //获取当前时间
        System.out.println("当前时间————————"+calendar.getTime());
        if(!calendar.getTime().before(new Date())) {
        	map.put("appid", config.getAppID());
        	map.put("partnerid", config.getMchID());
        	map.put("prepayid", tOrder.getExtension());
        	map.put("package", "Sign=WXPay");
        	map.put("noncestr", WXPayUtil.generateNonceStr());
        	map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));//单位为秒
        	map.put("sign",WXPayUtil.generateSignature(map,config.getKey(), WXPayConstants.SignType.MD5));
            map.put("extdata", attach);
            map.put("out_trade_no",outTradeNo);//系统订单号
        }else {
            Map<String, String> result = wxPayService.dounifiedOrder(attach,totalFee,outTradeNo);//预付订单接口调用
            //返回APP端的数据
            //参加调起支付的签名字段有且只能是6个，分别为appid、partnerid、prepayid、package、noncestr和timestamp，而且都必须是小写
            map.put("appid", result.get("appid"));
            map.put("partnerid", result.get("mch_id"));
            map.put("prepayid", result.get("prepay_id"));
            map.put("package", "Sign=WXPay");
            map.put("noncestr", result.get("nonce_str"));
            map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));//单位为秒
            //这里不要使用请求预支付订单时返回的签名
            map.put("sign",WXPayUtil.generateSignature(map,config.getKey(), WXPayConstants.SignType.MD5));
            map.put("extdata", attach);
            map.put("out_trade_no",outTradeNo);//系统订单号
		}
        return Result.success(map);
    }
    public static void main(String[] args) {
        Calendar instance = Calendar.getInstance();
        System.out.println("instance.getTime() = " + instance.getTime());
    	System.out.println( String.valueOf(new BigDecimal("0.01").multiply(new BigDecimal(100))));
	}
    /**
     * 支付异步结果通知，我们在请求预支付订单时传入的地址
     * 官方文档 ：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
     */
    @ApiOperation("回调接口")
    @RequestMapping(value = "/notify.json", method = {RequestMethod.GET, RequestMethod.POST})
    public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("支付回调！:"+sb);
            resXml = sb.toString();
            String result = wxPayService.payBack(resXml);
            return result;
        } catch (Exception e) {
            System.out.println("微信手机支付失败:" + e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }
    /**
     * 查询支付订单
     * 官方文档 ：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
     */
    @ApiOperation("订单查询接口")
    @RequestMapping(value = "/orderQuery", method = {RequestMethod.GET})
    public Result orderQuery(String OrderNumber) throws Exception {
    	PayResultVo payResult = wxPayService.payResult(OrderNumber);
    	if(ObjectUtils.isEmpty(payResult)) {
    		 return Result.error(null);
    	}
        return Result.success(payResult);
    }

//    @ApiOperation("测试")
//    @RequestMapping(value = "/testorderQuery", method = {RequestMethod.GET})
//    public void testorderQuery() {
//         //查询订单数据
//        wxPayService.test();
//        return ;
//    }
}